<template>
	<view>
		<ScrollPage @scrolltolower="nextPage">
			<template #content>
				<view >
					<!-- 搜索条件 -->
					<view class="w100" style="padding: 10px 15px 25px 15px">
						<up-form labelPosition="left" labelWidth="110" labelAlign="right">
							<up-form-item label="昵称：">
								<up-input border="surround" v-model="query.nickname" clearable></up-input>
							</up-form-item>
							<up-form-item label="创建时间：">
								<view class="w100 relative">
									<up-input border="surround"  v-model="query.date"></up-input>
									<view class="hw100  bg-transparency absolute" style="height: 40px; left:0; top:0;" @click="showPicker"></view>
								</view>
							</up-form-item>
						</up-form>
						<view class="w100 text-center">
							<button class="cu-btn line-gray" @click="searchClean">
								<text class="iconfont icon-delete margin-right-10"></text> 
								<text>重<text class="padding-lr-20"></text>置</text>
							</button>
							<text class="padding-lr-20"></text>
							<button class="cu-btn line-keyblue " @click="confirmSearch">
								<text class="iconfont icon-sousuo margin-right-10"></text> 
								<text>搜<text class="padding-lr-20"></text>索</text>
							</button>
						</view>
					</view>
					<!-- 内容区 -->
					<template v-if="dataList.length > 0">
						<view class="outline">
							<template v-for="(item,index) in dataList" :key="item.id">
								<view class="flex-row row" style="padding: 15px 5px;">
									<!-- 左边 -->
									<view class="flex-col">
											<MeImage   :src="item.avatar" width="48px" height="48px" radius="5" @click="previewSingleImage(item.avatar)"></MeImage >
											<MeImage   :src="item.nationalFlagUrl" width="48px" height="48px"  mode="aspectFit"></MeImage >
									</view>
									<!-- 右边 -->
									<view class="flex-col flex-sub margin-left-15 relative">
										 <view class="absolute padding-10 text-gray font-s15 " style="top: 5px;right: 5px;">
                                           <text>{{ index + 1 }}</text>
										</view>
										<view>
											<text class="text-bold">昵称:</text>
											<text class="margin-left-10 font-s36 text-lightGreyblue text-bold">{{item.nickname}}</text>
										</view>
										<view v-if="item.nationality" class="margin-tb-5" >
											<text class="text-bold">国籍:</text>
											<text class="margin-left-10 ">{{item.nationality}}</text>
											<text class="margin-left-10 text-gray font-s22">({{item.countryCode}})</text>
										</view>
										<view class="margin-tb-5" >
											<text class="text-bold">用户ID:</text>
											<text class="margin-left-10">{{item.userId}}</text>
										</view>
										<view class="margin-tb-5" >
											<text class="text-bold">生日:</text>
											<text class="margin-left-10">{{item.birthday}}</text>
										</view>
										<view class="flex-col  margin-tb-5" >
											<text class="text-bold font-s32">视频</text>
											<template v-if="item.posterUrl">
												<view style="width: 148px; height: 148px;"  @click="toPlay(item.videoUrl, item.posterUrl)">
													<MeImage :src="item.posterUrl" width="148px" height="148px" radius="5"></MeImage >
												</view>
											</template>
											<template v-else>
												<view class="relative solid-border-gray91 radius-10" style="width: 148px; height: 148px">
													<text class="iconfont icon-zanwutupian absolute" style="color: #E8E8E8; font-size: 58px; top: 39px; left: 49px"></text> 
												</view>
											</template>
										</view>
										<view class="margin-tb-5" >
											<text class="text-bold">文件大小:</text>
											<text class="margin-left-10">{{ (item.fileSize / 1024 / 1024).toFixed(2) }}M </text>
										</view>
										<view class="margin-tb-5" >
											<text class="text-bold">创建时间:</text>
											<text class="margin-left-10">{{ item.createTime }}</text>
										</view>
										<template v-if="item.updateTime">
											<view class=" margin-tb-5" >
												<text class="text-bold">更新时间:</text>
												<text class="margin-left-10">{{ item.updateTime }}</text>
											</view>
										</template>
										<view class=" margin-tb-5 flex-row" >
											<button class="cu-btn sm line-lightBlue"  @click="createPoster(item.id)">生成封面</button>
											<button class="cu-btn sm line-gray41 margin-lr-10"  @click="videoTranscode(item.id)">H.264编码</button>
											<button class="cu-btn sm line-purple"  @click="replaceVideo(item.id)">更换视频</button>
										</view>
									</view>
								</view>
							</template>
						</view>
						<view v-if="!loadding" class="h600 flex-col align-center">
							<view class="h64"></view>
							<button class="cu-btn line-blue" :disabled="dataList.length >= query.totalSize" @click="nextPage">加载更多数据</button>
						</view>
					</template>
					<!-- 暂无数据 -->
					<template v-else>
                        <view v-if="!loadding" class="h300 w100 flex-col-center text-gray81">
							<text class="iconfont icon-zanwushuju2" style="font-size: 125px;"></text>
						</view>
					</template>
				</view>
			</template>
		</ScrollPage>
		<up-datetime-picker ref="datePicker"  :formatter="formatter"    :show="showDatetime"  @cancel="cancelPicker" v-model="dataPickerValue"  
	   					cancelColor="red" @confirm="confirmSelectDate" mode="date"></up-datetime-picker>
		<!-- 更换视频提示 -->
		<view class="cu-modal" :class="isShowReplaceModel ? 'show' : '' ">
			<view class="cu-dialog bg-white">
				<view class="padding-25 font-s38">
					<text>提示</text>
				</view>
				<view class="padding-25 text-center font-s32">
					<text>确定更换视频?</text>
				</view>
				<view class="text-right margin-tb-20">
					<button class="cu-btn line-gray"  @click="isShowReplaceModel=false">取消</button>
					<button class="cu-btn line-blue margin-lr-20"  @click="confirmReplace">确定</button>
				</view>
			</view>
		</view> 
	</view>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { onLoad } from "@dcloudio/uni-app"
import { storeToRefs } from 'pinia'
import { showError } from '@/utils/msg-show'
import { previewSingleImage } from '@/utils/img'
import { formatter, convertDateFormat } from '@/utils/util'
import { navigate } from "@/security/router"
import { textToUrlCode } from "@/utils/strUtil"
import { urls } from "@/security/paths"
import { chooseVideo } from '@/utils/file'
import { createPosterApi, videoTranscodeApi, videoReplaceApi } from '@/api/anchor/video'

import { useAnchorVideoStore } from '@/store'

const anchorVideoStore = useAnchorVideoStore()
const { query, dataList } = storeToRefs(anchorVideoStore)

const loadding = ref(false)

const datePicker = ref()
const showDatetime = ref(false)
const today = new Date()
const dataPickerValue = ref(today.getTime())

const isShowReplaceModel = ref(false)
const replaceForm = reactive<any>({
	userId: "",
	videoId: "",
	videoFile: null,
})

// 显示picker
function showPicker(){
    uni.hideTabBar({
		animation:true,
		success: ()=>{
            showDatetime.value = true
		}
	})
}

// 取消picker窗口
function cancelPicker(){
  	uni.showTabBar({
		animation:true,
		success: ()=>{
			showDatetime.value = false
		}
	})
}


// 确定选择日期
function confirmSelectDate(val: any){
	const timestamp = val.value
    const date = new Date(timestamp)
    query.value.date = convertDateFormat(date)
	// animation	是否需要动画效果，仅小程序支持
	uni.showTabBar({
		animation:true,
		success: ()=>{
              showDatetime.value = false
		}
	})
}

// 生成封面
async function createPoster(videoId: number){
  const index = dataList.value.findIndex( (el: any) => { 
	 return el.id === videoId
  })
  if(index != -1){
       const obj = dataList.value[index]
	   uni.showLoading({mask: true})
       await createPosterApi({userId: obj.userId, videoId}).then((res: any) => {
            obj.posterUrl = res.data
			dataList.value[index] = obj
	   }).catch((err:any) => {
		  showError(err.msg || err.errMsg || err)
	   }).finally(()=>{
          uni.hideLoading()
	   })
  }
}

// 转码
async function videoTranscode(videoId: number){
  const index = dataList.value.findIndex( (el: any) => { 
	 	return el.id === videoId
   })
  if(index != -1){
       const obj = dataList.value[index]
	   uni.showLoading({mask: true})
       await videoTranscodeApi({userId: obj.userId, videoId}).then((res: any) => {
            obj.videoUrl = res.data.videoUrl
            obj.fileSize = res.data.fileSize
            obj.updateTime = res.data.updateTime
			dataList.value[index] = obj
	   }).catch((err:any) => {
		  showError(err.msg || err.errMsg || err)
	   }).finally(()=>{
          uni.hideLoading()
	   })
  }
}

// 更换视频
function replaceVideo(videoId: number){
	const target = dataList.value.find((el: any) => el.id === videoId)
		if(target){
			replaceForm.userId = target.userId
			replaceForm.videoId = target.id
			chooseVideo((videoPath:string) => {
				replaceForm.videoFile = videoPath
                isShowReplaceModel.value = true
			})
	}
}

// 确定更换视频
async function confirmReplace(){
	isShowReplaceModel.value = false
	uni.showLoading({mask: true})
	await videoReplaceApi(replaceForm.videoFile, { ...replaceForm, videoFile: null}).then((res: any) => {
        const target = dataList.value.find((el: any) => el.id === replaceForm.videoId)
		const jsonData = JSON.parse(res);
		if(target){
			target.updateTime = jsonData.data.updateTime
			target.posterUrl = jsonData.data.posterUrl
			target.fileSize = jsonData.data.fileSize
		}
	}).catch((err:any) => {
		showError(err.msg || err.errMsg || err)
	}).finally(()=>{
		uni.hideLoading()
	})
}

// 跳转到播放视频
function toPlay(videoUrl: string, posterUrl: string){
  navigate(`${urls.Play}?videoUrl=${textToUrlCode(videoUrl)}&posterUrl=${textToUrlCode(posterUrl)}`)
}

// 确定搜索
async function confirmSearch(){
	dataList.value = []
    query.value.pageNum = 1
	await search()
}

// 下一页
async function nextPage(){
	if(dataList.value.length < query.value.totalSize){
		query.value.pageNum = query.value.pageNum + 1
		await search()
	}
}

// 搜索
async function search(){
	query.value.totalSize = undefined
	uni.showLoading({mask: true})
	loadding.value = true	
	await anchorVideoStore.getPage().finally(()=>{
		uni.hideLoading()
		loadding.value = false
	})
}

// 清空搜索条件
function searchClean(){
	query.value.nickname = ''
	query.value.date = ''
	confirmSearch()
}

onLoad( async () => {
   loadding.value = true		
   uni.showLoading({mask: true})
   anchorVideoStore.init().finally(()=>{
      uni.hideLoading()
	  loadding.value = false
   })
});
</script>